package org.ccay.mail.service.impl;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.async.IMessageSender;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.ioc.Ccay;
import org.ccay.core.log.ILogger;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.util.StringUtil;
import org.ccay.mail.MailVO;
import org.ccay.mail.MeetingMailEwsVO;
import org.ccay.mail.MeetingMailVO;
import org.ccay.mail.service.IMailService;

/**
 * 异步线程邮件服务
 * 
 * @author chaowangbang
 * @since 2011-11-21
 */
@Named("defaultMailService")
public class AsyncMailService implements IMailService, IMessageProcessor {
	private ILogger log = CcayLoggerFactory.getLogger("CcayMail");
	/**
	 * 使用基础邮件服务
	 */
	@Inject
	@Named("baseMailService")
	private IMailService mailService;
	/**
	 * 默认异步处理
	 */
	@Inject
	private IMessageSender messageSender;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.ccay.mail.service.IMailService#sendMail(www.ccay.org
	 * .ccay.mail.MailVO)
	 */
	public void sendMail(MailVO newMail) throws ApplicationException {
		// 构建异步消息
		AsyncMessage message = new AsyncMessage("Mail");
		message.setContent(newMail);

		log.debug("Before send mail message for async process.");

		messageSender.send(message);
	}

	public void sendMeetingMail(MeetingMailVO meetingMailVO)
			throws ApplicationException {
		// 构建异步消息
		AsyncMessage message = new AsyncMessage("Mail");
		message.setContent(meetingMailVO);

		log.debug("Before send meetingmail message for async process.");

		messageSender.send(message);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.ccay.async.IMessageProcessor#process(org.ccay
	 * .async.AsyncMessage)
	 */
	public void process(AsyncMessage message) throws ApplicationException {
		MailVO mail = (MailVO) message.getContent();

		IMailService mailService2Use = null;

		try {
			if (StringUtil.isNullOrEmpty(mail.getUseBean())) {
				mailService2Use = mailService;
			} else {
				mailService2Use = Ccay.getContext().getBean(mail.getUseBean(), IMailService.class);
			}

			mailService2Use.sendMail(mail);

		} catch (ApplicationException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
	}

}
